package com.saas.shopping.interceptor;

import common.BizException;
import common.ExceptionCode;
import common.JsonResult;
import common.UserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with IntelliJ IDEA.
 * User: ljc
 * Date: 2023/02/13 16:20
 * Description:
 * Version: V1.0
 *
 * @author: ljc
 */
@Configuration
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        String token = request.getHeader("token");
        //判断token为空则抛出异常
        if (StringUtils.isEmpty(token)){
            throw new BizException(ExceptionCode.NULL_TOKEN);
        }

        //把token传递给sso服务器,完成校验,校验成功,还获取User信息
        //向localhost:8090/user/queryUserByToken远程调用

        RestTemplate restTemplate=new RestTemplate();
        String url="http://localhost:8090/user/queryUserByToken";
        LinkedMultiValueMap<String, Object> values = new LinkedMultiValueMap<>();
        values.add("phone","134");

        //指定请求头
        HttpHeaders httpHeaders=new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        httpHeaders.set("token",token);
        HttpEntity httpEntity = new HttpEntity(values,httpHeaders);
        JsonResult jsonResult = restTemplate.postForObject(url, httpEntity, JsonResult.class);
        Object data = jsonResult.getData();
        //在放行前 将用户信息放入ThreadLocal
        UserThreadLocal.set(data);
        if (jsonResult.getCode() == 200){
            return true;
        }
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //当请求完成后,从ThreadLocal中把用户信息清楚
        UserThreadLocal.remove();
    }
}
